Variables in Python
Definition: A variable is a named container that stores data values in memory. In Python, you don't need to declare the variable type explicitly - it's dynamically typed.
💡 Beginner's Tip: Think of a variable like a labeled box. You can put different things in the box (numbers, text, etc.), and you can always access what's inside by using the label (variable name). Unlike some languages, Python automatically figures out what type of data you're storing!
Variable Naming Rules:
- Must start with a letter or underscore (_)
- Can contain letters, numbers, and underscores
- Case-sensitive (age and Age are different)
- Cannot use Python keywords (like if, for, while)
Example: Creating Variables
# Variable assignment - just use = to store a value
name = "Alice" # Stores text (string)
age = 25 # Stores a whole number (integer)
height = 5.6 # Stores a decimal number (float)
is_student = True # Stores True or False (boolean)
# Multiple assignment - assign multiple variables at once
x, y, z = 10, 20, 30
# You can change variable values anytime
age = 26 # age is now 26 instead of 25
Data Types in Python
1. Numeric Types
Definition: Numeric types represent numbers. Python has three numeric types: int (integers), float (decimal numbers), and complex (complex numbers).
💡 Simple Explanation: Numeric types are just different ways to represent numbers:
- int - Whole numbers like 5, 100, -42 (no decimal point)
- float - Numbers with decimals like 3.14, 5.5, -0.001
- complex - Advanced math numbers (used in engineering, rarely needed by beginners)
Examples of Numeric Types
# Integer (int)
age = 25
population = 7800000000
# Float
temperature = 36.6
pi = 3.14159
# Complex
z = 3 + 5j
print(z.real) # Output: 3.0
print(z.imag) # Output: 5.0
2. Sequence Types
Definition: Sequence types are ordered collections of items. They include strings (str), lists (list), and tuples (tuple). Sequences support indexing and slicing.
💡 Simple Explanation: Sequences are like containers that hold multiple items in order:
- String - A sequence of characters (text). Example: "Hello"
- List - A changeable collection in square brackets []. You can add, remove, or modify items
- Tuple - A fixed collection in parentheses (). Once created, you cannot change it
Examples of Sequence Types
# String (str) - immutable sequence of characters
message = "Hello, Python!"
print(message[0]) # Output: H
print(message[0:5]) # Output: Hello
# List (list) - mutable ordered collection
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
fruits[0] = "apricot"
print(fruits) # Output: ['apricot', 'banana', 'cherry', 'date']
# Tuple (tuple) - immutable ordered collection
coordinates = (10, 20, 30)
print(coordinates[1]) # Output: 20
# coordinates[0] = 15 # This would cause an error!
3. Mapping Type
Definition: A mapping type stores data in key-value pairs. The dictionary (dict) is Python's only built-in mapping type. Keys must be unique and immutable.
💡 Simple Explanation: A dictionary is like a real dictionary or a phone book. Instead of looking up words to find meanings, you look up keys to find values. For example:
- Key: "name" → Value: "John"
- Key: "age" → Value: 25
Examples of Dictionary
# Dictionary (dict)
student = {
"name": "John",
"age": 20,
"grade": "A",
"courses": ["Math", "Science"]
}
print(student["name"]) # Output: John
student["age"] = 21 # Update value
student["city"] = "NYC" # Add new key-value pair
4. Boolean Type
Definition: Boolean type represents truth values: True or False. Booleans are often used in conditional statements and comparisons.
💡 Simple Explanation: Boolean is the simplest data type - it only has two values: True or False (like a light switch: on or off). It's used for making decisions in your code. For example:
- Is the user logged in? True or False
- Is the temperature above 30? True or False
- Did the student pass? True or False
Examples of Boolean
# Boolean values
is_active = True
is_deleted = False
# Boolean from comparisons
result = (10 > 5) # True
is_equal = (5 == 10) # False
# Boolean conversion
print(bool(1)) # True
print(bool(0)) # False
print(bool("")) # False (empty string)
print(bool("Hello")) # True
5. Set Types
Definition: Sets are unordered collections of unique elements. Python has two set types: set (mutable) and frozenset (immutable). Sets are useful for removing duplicates and performing mathematical operations.
💡 Simple Explanation: Think of a set like a bag of unique items. Key features:
- No duplicates: If you try to add the same item twice, it only keeps one copy
- No specific order: Items aren't stored in any particular sequence
- Fast lookups: Very efficient for checking if something exists
Examples of Set Types
# Set (set) - mutable, unordered, unique elements
colors = {"red", "blue", "green"}
colors.add("yellow")
colors.add("red") # Won't be added (duplicate)
print(colors) # Output: {'red', 'blue', 'green', 'yellow'}
# Set operations
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 | set2) # Union: {1, 2, 3, 4, 5, 6}
print(set1 & set2) # Intersection: {3, 4}
# Frozenset - immutable set
frozen = frozenset([1, 2, 3])
# frozen.add(4) # This would cause an error!
6. Binary Types
Definition: Binary types are used to work with binary data (bytes). Python has three binary types: bytes (immutable), bytearray (mutable), and memoryview (memory view object).
💡 Simple Explanation: Binary types work with raw data (0s and 1s) - the language computers understand:
- bytes: Fixed binary data (like reading a file)
- bytearray: Binary data you can modify
- memoryview: Advanced feature for efficient memory handling
Examples of Binary Types
# Bytes (bytes) - immutable sequence of bytes
b1 = b"Hello"
b2 = bytes([65, 66, 67]) # ABC in ASCII
print(b1) # Output: b'Hello'
print(b2) # Output: b'ABC'
# Bytearray (bytearray) - mutable sequence of bytes
ba = bytearray(b"Hello")
ba[0] = 74 # Change 'H' to 'J'
print(ba) # Output: bytearray(b'Jello')
# Memoryview - allows access to internal data of an object
mv = memoryview(bytes(5))
print(mv[0]) # Output: 0
Operators in Python
1. Arithmetic Operators
Definition: Arithmetic operators perform mathematical operations on numeric values.
💡 Simple Explanation: These are the basic math operations you learned in school, plus a few extras:
- +, -, *, / work just like in math class
- // (floor division) divides and rounds DOWN to nearest whole number
- % (modulus) gives you the remainder after division
- ** (exponent) raises a number to a power (like 2³ = 2**3 = 8)
| Operator | Name | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| - | Subtraction | 10 - 4 | 6 |
| * | Multiplication | 6 * 7 | 42 |
| / | Division | 15 / 4 | 3.75 |
| // | Floor Division | 15 // 4 | 3 |
| % | Modulus | 15 % 4 | 3 |
| ** | Exponentiation | 2 ** 3 | 8 |
Arithmetic Operators in Action
a = 20
b = 6
print("Addition:", a + b) # 26
print("Subtraction:", a - b) # 14
print("Multiplication:", a * b) # 120
print("Division:", a / b) # 3.333...
print("Floor Division:", a // b) # 3
print("Modulus:", a % b) # 2
print("Exponentiation:", a ** 2) # 400
2. Comparison Operators
Definition: Comparison operators compare two values and return a boolean result (True or False).
💡 Simple Explanation: These operators help you compare things and always give you True or False as an answer:
- == checks if two things are equal (not =, which assigns values!)
- != checks if two things are NOT equal
- >, <, >=, <= compare if one is bigger, smaller, or equal
| Operator | Name | Example | Result |
|---|---|---|---|
| == | Equal to | 5 == 5 | True |
| != | Not equal to | 5 != 3 | True |
| > | Greater than | 7 > 5 | True |
| < | Less than | 3 < 8 | True |
| >= | Greater than or equal to | 5 >= 5 | True |
| <= | Less than or equal to | 4 <= 3 | False |
Comparison Operators in Action
x = 10
y = 20
print(x == y) # False
print(x != y) # True
print(x > y) # False
print(x < y) # True
print(x >= 10) # True
print(y <= 15) # False
3. Assignment Operators
Definition: Assignment operators are used to assign values to variables. They can also perform operations and assign the result in one step.
💡 Simple Explanation: Assignment operators are shortcuts for common operations:
- x = 5 simply stores 5 in x
- x += 3 is a shortcut for x = x + 3 (add 3 to current value)
- x *= 2 is a shortcut for x = x * 2 (multiply current value by 2)
| Operator | Example | Equivalent to |
|---|---|---|
| = | x = 5 | x = 5 |
| += | x += 3 | x = x + 3 |
| -= | x -= 3 | x = x - 3 |
| *= | x *= 3 | x = x * 3 |
| /= | x /= 3 | x = x / 3 |
| //= | x //= 3 | x = x // 3 |
| %= | x %= 3 | x = x % 3 |
| **= | x **= 3 | x = x ** 3 |
Assignment Operators in Action
num = 10
print("Initial value:", num) # 10
num += 5
print("After += 5:", num) # 15
num *= 2
print("After *= 2:", num) # 30
num //= 4
print("After //= 4:", num) # 7
num **= 2
print("After **= 2:", num) # 49
4. Logical Operators
Definition: Logical operators are used to combine conditional statements and return boolean values.
💡 Simple Explanation: Logical operators let you combine multiple True/False conditions:
- and - Both conditions must be True (like "if it's sunny AND warm")
- or - At least one condition must be True (like "if you have cash OR credit card")
- not - Flips True to False and False to True (like "if it's NOT raining")
| Operator | Description | Example | Result |
|---|---|---|---|
| and | Returns True if both statements are true | True and False | False |
| or | Returns True if at least one statement is true | True or False | True |
| not | Reverses the boolean value | not True | False |
Logical Operators in Action
age = 25
has_license = True
# AND operator
can_drive = (age >= 18) and has_license
print("Can drive:", can_drive) # True
# OR operator
is_student = False
is_senior = False
gets_discount = is_student or is_senior
print("Gets discount:", gets_discount) # False
# NOT operator
is_raining = True
is_sunny = not is_raining
print("Is sunny:", is_sunny) # False
5. Membership Operators
Definition: Membership operators test whether a value is present in a sequence (string, list, tuple, set, or dictionary).
💡 Simple Explanation: These operators check if something exists inside a collection:
- in - Checks if an item is in the collection (returns True if found)
- not in - Checks if an item is NOT in the collection (returns True if not found)
- Is "apple" in my shopping list?
- Is "o" in the word "Hello"?
- Is this username NOT in the database?
| Operator | Description | Example |
|---|---|---|
| in | Returns True if value is found in the sequence | x in y |
| not in | Returns True if value is not found in the sequence | x not in y |
Membership Operators in Action
fruits = ["apple", "banana", "cherry"]
text = "Hello World"
# in operator
print("apple" in fruits) # True
print("grape" in fruits) # False
print("Hello" in text) # True
# not in operator
print("mango" not in fruits) # True
print("World" not in text) # False
# With dictionaries (checks keys)
person = {"name": "Alice", "age": 30}
print("name" in person) # True
6. Identity Operators
Definition: Identity operators compare the memory locations of two objects. They check if two variables refer to the same object in memory, not just equal values.
💡 Simple Explanation: Identity operators check if two variables point to the exact same object in computer memory:
- is - True if both variables are the SAME object (same memory location)
- is not - True if variables are DIFFERENT objects
- == checks if values are equal
- is checks if they're the same object
| Operator | Description | Example |
|---|---|---|
| is | Returns True if both variables refer to the same object | x is y |
| is not | Returns True if variables refer to different objects |